import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))

import requests
import json
from reqapi.api import BaseApi
from com.db.order_account_manager import OrderAccountManager

class ConfirmAndSendOfferApi(BaseApi):
    def execute(self, send_order_no_list):
        """
        确认发货并发送报价API
        
        Args:
            send_order_no_list: 需要发送的订单号列表
            
        Returns:
            bool: 是否成功
        """
        url = f"{self.BASE_URL}/api/youpin/bff/trade/v1/order/sell/delivery/confirmAndSendOfferList"
        
        data = {
            "sendOrderNoList": send_order_no_list,
            "Sessionid": self.device_id
        }
        headers = self.common_headers.copy()
        print("\n=== 请求信息 ===")
        print(f"请求URL: {url}")
        print(f"请求方法: POST")
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        print(f"请求数据: {json.dumps(data, indent=2, ensure_ascii=False)}")
        try:
            response = self.interceptor.send_request(url, json=data, headers=headers, need_encrypt=False)
            print("\n=== 响应信息 ===")
            if isinstance(response, dict):
                result = response
            elif hasattr(response, 'json'):
                result = response.json()
            else:
                result = response
            print(f"响应数据: {json.dumps(result, indent=2, ensure_ascii=False)}")
            if result.get('code') != 0:
                print(f"业务处理失败: {result.get('msg')}")
                return False
            return True
        except Exception as e:
            print(f"请求失败: {e}")
            return False


def main():
    """测试确认发货并发送报价API"""
    try:
        # 从数据库获取id为1的账号信息
        account_manager = OrderAccountManager()
        account = account_manager.get_account_by_id(1)
        
        if not account:
            raise Exception("未找到ID为1的账号信息")
        
        # 从账号信息中获取认证信息
        device_id = account.get("device_id", "")
        auth_token = account.get("uu_token", "")
        uk = account.get("uk", "")
        
        if not device_id or not auth_token or not uk:
            raise Exception("账号信息不完整，缺少必要的认证信息")
        
        # 确保auth_token格式正确
        if not auth_token.startswith("Bearer "):
            auth_token = f"Bearer {auth_token}"
        
        # 创建API实例
        api = ConfirmAndSendOfferApi(
            device_token=device_id,  # 使用 device_id 作为 device_token
            device_id=device_id,
            auth_token=auth_token,
            uk=uk
        )
        
        # 需要发送的订单号列表
        send_order_no_list = [
            "2025020210964853469",
            "2025020210964853470"
        ]
        
        # 调用API
        result = api.execute(send_order_no_list)
        
        # 打印结果
        print("\n=== 确认发货并发送报价结果 ===")
        print(f"处理结果: {'成功' if result else '失败'}")
        print(f"处理订单数量: {len(send_order_no_list)}")
        print("订单列表:")
        for order_no in send_order_no_list:
            print(f"- {order_no}")
        
    except Exception as e:
        print(f"测试失败: {str(e)}")


if __name__ == "__main__":
    main()
